<?php
/**
 * Author: xx.com
 */ 
namespace Shop\Controller;
use Think\Controller;
use Think\Page;

class GoodsController extends BaseController {

    /**
     * 析构流函数
     */
    public function  __construct() {   
        parent::__construct();    
        //$this->userLogic = new \Home\Logic\UsersLogic();
    }

    /**
     *  商品列表
     */
    public function shop_goods(){

        $p = I('p', 1, 'intval');
        $pagesize = I('pagesize', 10, 'intval');

        $where['shop_id'] = $this->shop_info['shop_id'];
        $where['shop_on_sale'] = 1;
        $shopGoodsModel = M('shop_goods');
        $count =  $shopGoodsModel->where($where)->count();

        $goods_list = $shopGoodsModel
            ->field('id, goods_id, store_count, add_time')
            ->where($where)
            ->order('add_time DESC')
            ->page($p, $pagesize)
            ->select();

        $goodsModel = M('goods');
        $warning_storage = tpCache('basic.warning_storage');
        foreach($goods_list as $key => &$val){
            $goods_info = $goodsModel->field('goods_name,goods_remark,shop_price,market_price,original_img')
                    ->where(array('goods_id'=>$val['goods_id']))->find();
            $val['goods_name'] = $goods_info['goods_name'];
            $val['goods_remark'] = $goods_info['goods_remark'];
            $val['shop_price'] = $goods_info['shop_price'];
            $val['market_price'] = $goods_info['market_price'];
            $val['original_img'] = parseMediaUrl($goods_info['original_img']);
            $val['need_repl'] = 0;
            if($val['store_count'] <= $warning_storage){
                $val['need_repl'] = 1;
            }
        }
        $page_info = array('count'=>$count, 'page_count'=>count($goods_list), 'p'=>I('p',1,'intval'), 'page_size'=>$pagesize);
        $this->returnInfo(1, '商品列表',  array('page_info'=>$page_info, 'list'=>$goods_list));
    }

    /**
     * 修改商品库存
     */
    public function update_store(){
        $shop_goods_id = I('shop_goods_id', 0, 'intval');
        if($shop_goods_id <= 0){
            $this->returnInfo(-1,"商品信息有误");
        }

        $shop_id = $this->shop_info['shop_id'];
        $shopGoodsModel =  M('shop_goods');
        $shop_goods = $shopGoodsModel->where(array('id'=>$shop_goods_id, 'shop_id'=>$shop_id))->find();

        if(!$shop_goods){
            $this->returnInfo(-1,"商品信息不存在");
        }

        if($shop_goods['shop_on_sale'] == 0){
            $this->returnInfo(-1,"商品未上架");
        }
        $store = I('store_count', 0, 'intval');
        if($store <= 0){
            $this->returnInfo(-1,"库存数量为大于0的整数");
        }

        $is_success = $shopGoodsModel->where(array('id'=>$shop_goods_id))->setField('store_count', $store);
        if($is_success === false){
            $this->returnInfo(-1,"操作失败");
        }
        $this->returnInfo(1,"操作成功");
    }

}